package com.liliudong.pinkyponk.api.admin.handler;

import com.liliudong.pinkyponk.core.constant.ResponseMessage;
import com.liliudong.pinkyponk.core.exception.PinkyPonkGloableException;
import com.liliudong.pinkyponk.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常
 *
 * @author liliudong
 * @date 2022-05-28 15:54
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(PinkyPonkGloableException.class)
    public ResponseEntity<?> pinkyPonkGloableExceptionHandler(PinkyPonkGloableException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getResponseMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<?> accessDeniedException(AccessDeniedException e) {
        log.error(e.getMessage(), e);
        return R.error(ResponseMessage.NO_PERMISSION);
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<?> usernameNotFoundExceptionHandler(UsernameNotFoundException e) {
        log.error(e.getMessage(), e);
        return R.error(ResponseMessage.USERNAME_NOT_FOUND);
    }

    @ExceptionHandler(LockedException.class)
    public ResponseEntity<?> lockedException(LockedException e) {
        log.error(e.getMessage(), e);
        return R.error(ResponseMessage.USER_LOCKED);
    }

    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<?> badCredentialsException(BadCredentialsException e) {
        log.error(e.getMessage(), e);
        return R.error(ResponseMessage.PASSWORD_INCORRECT);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<?> exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}
